#!/bin/bash

# iostat -kx 1
# avg-cpu:  %user   %nice %system %iowait  %steal   %idle
#            0.75    0.00    6.36   18.20    0.00   74.69
# 		1	2	3	4	5	6

# Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await  svctm  %util
# sda               0.00     0.00    0.00  136.63     0.00 63065.35   923.13   143.09 1416.26   7.28  99.41
# 1			2	3	4	5	6	7	8	9	10	11	12

plot() {
disk=$1
cpu=$2
suffix=$3
gnuplot <<EOF
set xlabel "time (s)"

set size 1
set terminal pngcairo size ${width:-1280}, 800
set terminal pngcairo size ${width:-1000}, 600

set grid

set output "iostat-bw$suffix.png"
set ylabel "throughput (MB/s)"
plot "$disk" using (\$7/1024) with linespoints pt 5 title "write MB/s", \
     "$disk" using (\$6/1024) with linespoints pt 4 title "read MB/s"

unset grid

set output "iostat-util$suffix.png"
set ylabel "percent"
set yrange [0:100]
unset clip
plot "$disk" using 12 with linespoints pt 5 ps 0.6 title "disk util", \
     "$cpu" using 1 with linespoints pt 4 ps 0.6 title "user", \
     "$cpu" using 2 with linespoints pt 4 ps 0.6 title "nice", \
     "$cpu" using 3 with linespoints pt 4 ps 0.6 title "system", \
     "$cpu" using 4 with linespoints pt 4 ps 0.6 title "iowait", \
     "$cpu" using 5 with linespoints pt 4 ps 0.6 title "steal", \
     "$cpu" using 6 with linespoints pt 4 ps 0.6 title "idle"

unset ylabel
set yrange [*:*]

set output "iostat-misc$suffix.png"
set ytics nomirror
set y2label "time"
set y2tics
plot "$disk" using  4 axis x1y1 with linespoints title "r/s", \
     "$disk" using  5 axis x1y1 with linespoints title "w/s", \
     "$disk" using  8 axis x1y1 with linespoints title "avgrq-sz", \
     "$disk" using  9 axis x1y1 with linespoints title "avgqu-sz", \
     "$disk" using 10 axis x1y2 with      points title "await", \
     "$disk" using 11 axis x1y2 with      points title "svctm"

EOF
}

test -s iostat || exit

[[ -f iostat-disk ]] || grep ${IOSTAT_DISK:-sda} iostat > iostat-disk
[[ -f iostat-cpu  ]] || grep -A1 avg-cpu iostat | grep -v '[a-z-]' > iostat-cpu

plot iostat-disk iostat-cpu

lines=$(wc -l iostat-disk | cut -f1 -d' ')

# if [[ $lines -gt 100 ]]; then
# tail -n 50 < iostat-disk > iostat-disk-50
# tail -n 50 < iostat-cpu > iostat-cpu-50
# plot iostat-disk-50 iostat-cpu-50 -50
# fi

# if [[ $lines -ge 100 ]]; then
# width=3200
# plot $trace iostat-disk iostat-cpu +
# fi
